//
//  ConsultingViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/4/13.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "ConsultingViewController.h"
#import "questionZixunViewController.h"
#import "xitongViewController.h"
#import "jiankangViewController.h"
#import "shanshiViewController.h"
#import "baikeViewController.h"

@interface ConsultingViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,weak)UITextField *searchTF;
@property (nonatomic,weak)UIButton *searchBtn;
@property (nonatomic,weak)UIView *searchView;

@property (nonatomic,weak)UITableView *questionTableView;
@property (nonatomic,strong)NSMutableArray *questionArray;
@property (nonatomic,assign)BOOL editingFlag;
@end

@implementation ConsultingViewController

-(NSMutableArray *)questionArray
{
    if(!_questionArray)
    {
        _questionArray = [NSMutableArray array];
    }
    return _questionArray;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.searchTF resignFirstResponder];
    self.questionTableView.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        self.searchView.frame = CGRectMake(0, kDeviceHeight - 95, kDeviceWidth, 50);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
   
    UITableView *tableViewq = [[UITableView alloc]initWithFrame:CGRectMake(0, kDeviceHeight / 2.0 - 50, kDeviceWidth, kDeviceHeight / 2.0 - 50) style:UITableViewStyleGrouped];
    tableViewq.delegate = self;
    tableViewq.dataSource =self;
    self.questionTableView = tableViewq;
    tableViewq.tag = 1;
    tableViewq.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tableViewq];
    tableViewq.hidden = YES;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, kDeviceWidth, 50)];
    titleLabel.text = @"常见问题";
    titleLabel.textColor = YMColor(107, 107, 107);
    titleLabel.backgroundColor = YMColor(245, 245, 245);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLabel];
    
    UIView *quesView = [[UIView alloc]initWithFrame:CGRectMake(0, 114, kDeviceWidth, kDeviceHeight / 2.0 - 164)];
    quesView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:quesView];
    
    CGFloat h = quesView.frame.size.height / 4.0;
    for(int i = 0;i < 4;i ++)
    {
        UIView *littltView = [[UIView alloc]initWithFrame:CGRectMake(0, h * i, kDeviceWidth, h)];
        littltView.tag = i + 1;
        [quesView addSubview:littltView];
        if(littltView.tag % 2 == 1)
        {
            littltView.backgroundColor = [UIColor whiteColor];
        }
        else
        {
            littltView.backgroundColor = YMColor(245, 245, 245);
        }
        if(littltView.tag == 1)
        {
            [self addNormalQuestionToView:littltView andQuestion:@"【系统】忘记密码怎么办？"];
        }
        if(littltView.tag == 2)
        {
            [self addNormalQuestionToView:littltView andQuestion:@"【健康】如何监测身体健康？"];
        }
        if(littltView.tag == 3)
        {
            [self addNormalQuestionToView:littltView andQuestion:@"【膳食】怎样知道我的饮食是否合适？"];
        }
        if(littltView.tag == 4)
        {
            [self addNormalQuestionToView:littltView andQuestion:@"【百科】怎样分享百科内容给朋友？"];
        }
    }
    
    UILabel *redLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, kDeviceHeight / 2.0 - 50, kDeviceWidth, 5.0)];
    redLabel.backgroundColor = YMColor(254, 204, 229);
    [self.view addSubview:redLabel];
    
     [self sousuoLayout];
    
}

-(void)sousuoLayout
{
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(0, kDeviceHeight - 95, kDeviceWidth, 50)];
    self.searchView = searchView;
    [self.view addSubview:self.searchView];
    [self.view bringSubviewToFront:self.searchView];
    
    UITextField *searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 0, kDeviceWidth / 4.0 * 3, 35)];
    searchTextField.placeholder = @"请输入您要搜索的问题";
    [searchTextField setValue:YMColor(195, 195, 195) forKeyPath:@"_placeholderLabel.textColor"];
    searchTextField.borderStyle = UITextBorderStyleRoundedRect;
    searchTextField.font = [UIFont systemFontOfSize:15.0];
    searchTextField.layer.borderWidth = 1.0;
    searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    searchTextField.layer.borderColor = [YMColor(188, 188, 188)CGColor];
    searchTextField.layer.cornerRadius = 5.0;
    
    self.searchTF = searchTextField;
    [self.searchView addSubview:searchTextField];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    searchButton.frame = CGRectMake(20 + kDeviceWidth / 4.0 * 3, 0, kDeviceWidth - (30 + kDeviceWidth / 4.0 * 3), 35);
    searchButton.backgroundColor = YMColor(251, 159, 206);
    [searchButton setTitle:@"搜 索" forState:UIControlStateNormal];
    [searchButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    searchButton.layer.cornerRadius = 5.0;
    self.searchBtn = searchButton;
    [self.searchView addSubview:searchButton];
    
    [searchButton addTarget:self action:@selector(clickSearchButton) forControlEvents:UIControlEventTouchUpInside];
    
    [searchTextField addTarget:self action:@selector(onEditing) forControlEvents:UIControlEventEditingDidBegin];
    [searchTextField addTarget:self action:@selector(endEditing) forControlEvents:UIControlEventEditingDidEnd];
}

-(void)addNormalQuestionToView:(UIView *)view andQuestion:(NSString *)quesString
{
    CGFloat h = view.frame.size.height;
    CGFloat w = view.frame.size.width;
    
    UIImageView *jiantouImageView = [[UIImageView alloc]initWithFrame:CGRectMake(w - 20 - h / 2.0 , h / 4.0, h / 2.0, h / 2.0)];
    jiantouImageView.image = [UIImage imageNamed:@"assistant_》gray"];
    [view addSubview:jiantouImageView];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, kDeviceWidth, h)];
    titleLabel.text = quesString;
    titleLabel.font = [UIFont systemFontOfSize:15.0];
    titleLabel.textColor = YMColor(107, 107, 107);
    [view addSubview:titleLabel];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, w, h)];
    btn.tag = view.tag;
    [view addSubview:btn];
    [btn addTarget:self action:@selector(clickNormalButton:) forControlEvents:UIControlEventTouchUpInside];
}
//点击常见问题按钮
-(void)clickNormalButton:(UIButton *)btn
{
    if(btn.tag == 1)
    {
        xitongViewController *xitong = [[xitongViewController alloc]init];
        [self.navigationController pushViewController:xitong animated:YES];
    }
    if(btn.tag == 2)
    {
        jiankangViewController *jiankang = [[jiankangViewController alloc]init];
        [self.navigationController pushViewController:jiankang animated:YES];
    }
    if(btn.tag == 3)
    {
        shanshiViewController *shanshi = [[shanshiViewController alloc]init];
        [self.navigationController pushViewController:shanshi animated:YES];
    }
    if(btn.tag == 4)
    {
        baikeViewController *baike = [[baikeViewController alloc]init];
        [self.navigationController pushViewController:baike animated:YES];
    }
}

//点击搜索按钮
-(void)clickSearchButton
{
    
    [self.searchTF resignFirstResponder];
    [UIView animateWithDuration:0.1 animations:^{
        self.searchView.frame = CGRectMake(0, kDeviceHeight - 95, kDeviceWidth, 50);
    }];
    [self.questionArray removeAllObjects];
    [self.questionTableView reloadData];
  
    if(![self.searchTF.text isEqualToString:@""])
    {
        [MBProgressHUD showMessage:@"正在拼命加载,请稍后..."];
        NSString *urlString = @"http://120.24.178.16:8080/Health/baby/getPregnancyhelper.do";
        NSURL *url = [[NSURL alloc]initWithString:urlString];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
        
        request.HTTPMethod = @"POST";
        NSString *str = [NSString stringWithFormat:@"keyword=%@",self.searchTF.text];
        
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        
        NSOperationQueue *queue = [NSOperationQueue mainQueue];
        
        
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            if (data)
            {
                [MBProgressHUD hideHUD];
                // 请求成功
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSArray *questionArr = [dict objectForKey:@"data"];
                if(questionArr.firstObject == nil)
                {
                    [MBProgressHUD showError:@"没有找到您要搜索的内容!"];
                }
                else
                {
                    for(NSDictionary *ddd in questionArr)
                    {
                        [self.questionArray addObject:ddd];
                    }
                    self.questionTableView.hidden = NO;
                    [self.questionTableView reloadData];
                }
            }
        }];
    }
    else
    {
        [MBProgressHUD showError:@"请输入您要搜索的内容"];
    }
}

#pragma mark -- tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.questionArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *myCell = @"myCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myCell];
    if (!cell) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myCell];
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        cell.textLabel.font = [UIFont systemFontOfSize:14.0];
        cell.textLabel.textColor = [UIColor colorWithRed:170 / 255.0 green:170 / 255.0 blue:170 / 255.0 alpha:1.0];

        cell.textLabel.highlightedTextColor = [UIColor colorWithRed:252 / 255.0 green:160 / 255.0 blue:207 / 255.0  alpha:1.0];
        cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:252 / 255.0 green:160 / 255.0 blue:207 / 255.0  alpha:1.0];
        
    }
    NSDictionary *dict = self.questionArray[indexPath.row];
    cell.textLabel.text = [dict objectForKey:@"question"];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    questionZixunViewController *question = [[questionZixunViewController alloc]init];
    [self.navigationController pushViewController:question animated:YES];
    NSDictionary *dict = self.questionArray[indexPath.row];
    question.questionStr = [dict objectForKey:@"answer"];
}

-(void)onEditing
{
    self.editingFlag = YES;
    
}


-(void)endEditing
{
    self.editingFlag = NO;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self regNotification];
    self.editingFlag = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self unregNotification];
    
}

- (void)regNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)unregNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [self.view setNeedsDisplay];
}
#pragma mark - notification handler

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
    
    CGRect homeView = self.searchView.frame;
    
    if(self.editingFlag == YES)
    {
        
        if(SYDevice6p)
        {
            homeView.origin.y += yOffset + 18;
        }
        else if(SYDevice6)
        {
            homeView.origin.y += yOffset + 24;
        }
        else if(SYDevice5)
        {
            homeView.origin.y += yOffset + 30;
        }
        else
        {
            homeView.origin.y += yOffset + 30;
        }
        [UIView animateWithDuration:duration animations:^{
//            self.searchView.frame = CGRectMake(0, homeView.origin.y, kDeviceWidth, 50);
            self.searchView.frame = homeView;
            self.questionTableView.hidden = YES;
            
        }];
    }
    
}


@end
